// 管理员考勤管理内容组件
Vue.component('admin-attendance-content', {
  data() {
    return {
      records: [],
      searchName: '',
      searchStatus: '',
      searchDate: '',
      searchDepartment: '',
      currentPage: 1,
      pageSize: 10,
      totalRecords: 0,
      // 在data中定义状态选项
      statusOptions: [
        { label: '正常', value: 'present' },
        { label: '迟到', value: 'late' },
        { label: '缺勤', value: 'absent' },
        { label: '早退', value: 'early_leave' }
      ],
      // 部门选项
      departmentOptions: []
    };
  },
  async mounted() {
    // 组件挂载后先加载部门数据，再获取考勤数据
    await this.loadDepartments();
    this.fetchAttendanceData();
  },
  template: `
    <div style="padding: 32px; width: 100%; box-sizing: border-box;">
      <el-card shadow="hover" style="width: 100%;">
        <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">考勤管理</div>
        <div style="display: flex; align-items: center; margin-bottom: 12px;">
          <el-input v-model="searchName" placeholder="按姓名查询" style="width: 140px; margin-right: 8px;" size="small" clearable></el-input>
          <el-select v-model="searchDepartment" placeholder="按部门查询" style="width: 120px; margin-right: 8px;" size="small" clearable>
            <el-option v-for="option in departmentOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
          <el-select v-model="searchStatus" placeholder="按状态查询" style="width: 120px; margin-right: 8px;" size="small" clearable>
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
          <el-date-picker v-model="searchDate" type="date" placeholder="按日期查询" style="width: 150px; margin-right: 8px;" value-format="yyyy-MM-dd" size="small"></el-date-picker>
          <el-button type="primary" size="small" @click="handleFilter">查询</el-button>
          <el-button size="small" @click="handleReset" style="margin-left: 8px;">重置</el-button>
        </div>
        <el-table :data="records" style="width: 100%; margin-top: 10px;">
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="date" label="日期" width="120"></el-table-column>
          <el-table-column prop="checkIn" label="签到时间" width="120"></el-table-column>
          <el-table-column prop="checkOut" label="签退时间" width="120"></el-table-column>
          <el-table-column prop="status" label="状态" width="100"></el-table-column>
        </el-table>
        <div style="margin: 18px 0 0; text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalRecords"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  `,
  methods: {
    // 加载部门数据
    async loadDepartments() {
      try {
        const response = await departmentAPI.getDepartments();
        this.departmentOptions = (response.data.departments || []).map(dept => ({
          label: dept.name,
          value: dept.name
        }));
      } catch (error) {
        console.error('加载部门数据失败:', error);
        this.$message.error('加载部门数据失败');
      }
    },
    
    // 获取考勤数据
    fetchAttendanceData() {
      const params = {
        page: this.currentPage,
        per_page: this.pageSize
      };
      
      // 添加搜索参数
      if (this.searchName) {
        params.name = this.searchName;
      }
      if (this.searchDepartment) {
        params.department = this.searchDepartment;
      }
      if (this.searchStatus) {
        params.status = this.searchStatus;
      }
      if (this.searchDate) {
        params.date = this.searchDate;
      }
      
      attendanceAPI.getAttendances(params)
        .then(response => {
            // 转换API返回的数据为组件需要的格式
            const data = response.data;
            this.records = data.attendances.map(item => {
              let checkIn = '-';
              let checkOut = '-';
              let status = '正常';
              
              // 格式化签到时间
              if (item.check_in_time) {
                const checkInTime = new Date(item.check_in_time);
                checkIn = `${checkInTime.getHours().toString().padStart(2, '0')}:${checkInTime.getMinutes().toString().padStart(2, '0')}`;
              }
              
              // 格式化签退时间
              if (item.check_out_time) {
                const checkOutTime = new Date(item.check_out_time);
                checkOut = `${checkOutTime.getHours().toString().padStart(2, '0')}:${checkOutTime.getMinutes().toString().padStart(2, '0')}`;
              }
              
              // 处理状态
              if (item.status) {
                switch (item.status) {
                  case 'present':
                    status = '正常';
                    break;
                  case 'late':
                    status = '迟到';
                    break;
                  case 'absent':
                    status = '缺勤';
                    break;
                  case 'early_leave':
                    status = '早退';
                    break;
                  default:
                    status = '正常';
                }
              }
              
              return {
                id: item.id,
                name: item.name || '',
                date: item.date,
                checkIn: checkIn,
                checkOut: checkOut,
                status: status
              };
            });
            
            // 更新分页信息
            this.totalRecords = data.pagination ? data.pagination.total : data.total || 0;
            this.currentPage = data.pagination ? data.pagination.page : data.page || 1;
        })
        .catch(error => {
          console.error('获取考勤数据错误:', error);
          this.$message.error(error.message || '获取考勤数据失败');
        });
    },
    
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchAttendanceData();
    },
    
    handleFilter() {
      this.currentPage = 1;
      this.fetchAttendanceData();
    },
    
    handleReset() {
      // 重置所有搜索条件
      this.searchName = '';
      this.searchStatus = '';
      this.searchDate = '';
      this.searchDepartment = '';
      this.currentPage = 1;
      
      // 重新获取数据
      this.fetchAttendanceData();
    }
  }
});
